﻿namespace SimpleX
{
    public class WebsocketClientCollection
    {
        private static List<WebsocketClient> _clients = new List<WebsocketClient>();
        private static object locker = new object();

        public static List<string> GetAllClientIds()
        {
            return _clients.Select(x => x.ClientId).ToList();
        }

        public static void Add(WebsocketClient client)
        {
            lock (locker)
            {
                _clients.Add(client);
            }
        }

        public static void RemoveSameId(WebsocketClient client)
        {
            lock (locker)
            {
                _clients.RemoveAll(x => x.ClientId == client.ClientId);
            }
        }

        public static void Remove(WebsocketClient client)
        {
            lock (locker)
            {
                _clients.Remove(client);
            }
        }

        public static WebsocketClient Get(string clientId)
        {
            var client = _clients.FirstOrDefault(c => c.ClientId == clientId);
            return client;
        }

        public static async Task<bool> Send<T>(string cliendId, WebsocketMessage<T> message)
        {
            var client = Get(cliendId);
            if (client != null)
            {
                await client.SendMessageAsync(message.ToJson());
                return true;
            }
            return false;
        }
    }
}